#!/usr/bin/env node

//通过命令行交互询问用户问题
//根据用户回答的结果输出对应的文件

const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const ejs = require('ejs')

function dataProcessFn(temPath, distPath, content) {
  fs.readdir(temPath, (err, files) => {
    if (err) throw err
    files.forEach(file => {
      const f = fs.statSync(path.join(temPath, file))
      if (f.isDirectory()) {
        dataProcessFn(path.join(temPath, file), path.join(distPath, file), content)
        fs.mkdirSync(path.join(distPath, file))
      } else {
        ejs.renderFile(path.join(temPath, file), content, (err, data) => {
          if (err) throw err
          fs.writeFileSync(path.join(distPath, file), data)
        })
      }
      // fs.stat(path.join(temPath, file), (err, result) => { 方式二
      //   if (err) throw err
      //   if (result.isDirectory()) {
      //     dataProcessFn(path.join(temPath, file), path.join(distPath, file), content)
      //     fs.mkdirSync(path.join(distPath, file))
      //   } else {
      //     ejs.renderFile(path.join(temPath, file), content, (err, res) => {
      //       if (err) throw err
      //       fs.writeFileSync(path.join(distPath, file), res)
      //     })
      //   }
      // })
    })
  })
}

inquirer.prompt([
  {
    type: 'input',
    name: 'name',
    message: 'project name?'
  },
  {
    type: 'input',
    name: 'title',
    message: 'project title?'
  }
]).then(result => {
  const temPath = path.join(__dirname, 'templates')
  const distPath = process.cwd()
  // fs.readdir(temPath, (err, files) => {
  //   if (err) throw err
  //   files.forEach(file => {
  //     ejs.renderFile(path.join(temPath, file), result, (err, data) => {
  //       if (err) throw err
  //       // console.log(data)
  //       fs.writeFileSync(path.join(distPath, file), data)
  //     })
  //   })
  // })
  dataProcessFn(temPath, distPath, result)
})